from torch import nn

from training.models.senet import SEResNetBlock

__all__ = ['seresnetcolorspace']


class SEResnetSpaceGenerator(nn.Module):

    def __init__(self, inplanes, planes):
        super(SEResnetSpaceGenerator, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, 64, 3, 1, 1)
        self.act1 = nn.LeakyReLU(True)

        self.block1 = SEResNetBlock(64, 64, 1, 16)
        self.block2 = SEResNetBlock(64, 64, 1, 16)
        self.block3 = SEResNetBlock(64, 64, 1, 16)
        self.block4 = SEResNetBlock(64, 64, 1, 16)
        self.block5 = SEResNetBlock(64, 64, 1, 16)

        self.conv2 = nn.Conv2d(64, 64, 3, 1, 1)
        self.bn2 = nn.BatchNorm2d(64)

        self.conv3 = nn.Conv2d(64, 64, 3, 1, 1)
        self.act3 = nn.LeakyReLU(True)
        self.conv4 = nn.Conv2d(64, planes, 3, 1, 1)

    def forward(self, x):
        x = self.conv1(x)
        x = self.act1(x)
        identity = x

        x = self.block1(x)
        x = self.block2(x)
        x = self.block3(x)
        x = self.block4(x)
        x = self.block5(x)

        x = self.conv2(x)
        x = self.bn2(x)
        x = x + identity

        x = self.conv3(x)
        x = self.act3(x)
        x = self.conv4(x)

        return x


class SEResnetColorSpace(nn.Module):

    def __init__(self, feature_extractor, in_channels, num_classes, pretrained=False):
        super(SEResnetColorSpace, self).__init__()
        self.compact = SEResnetSpaceGenerator(in_channels, 3)
        self.features = feature_extractor(pretrained=pretrained, num_classes=num_classes)

    def forward(self, x):
        x = self.compact(x)
        x = self.features(x)
        return x


def seresnetcolorspace(feature_extractor, in_channels=3, num_classes=1000, pretrained=False):
    model = SEResnetColorSpace(feature_extractor, in_channels=in_channels, num_classes=num_classes, pretrained=pretrained)
    model.default_cfg = model.features.default_cfg
    return model
